package com.metadata_system.api_server.socket_server;


import com.alibaba.fastjson.JSON;
import com.corundumstudio.socketio.SocketIOClient;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import com.metadata_system.common.dto.ApiResult;
import com.metadata_system.common.dto.JwtToken;
import com.metadata_system.common.service.TokenValidate;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

@Component
@Slf4j
public class MyClientUser {

    @Autowired
    TokenValidate tokenValidate;


    public static Map<UUID, SocketIOClient> AllSocketMap = new ConcurrentHashMap<>();
    private static Map<Integer, SocketIOClient> LoginSocketMap = new ConcurrentHashMap<>();
    private static Map<UUID, LoginUserInfo> LoginUserInfoMap = new ConcurrentHashMap<>();

    /**
     * 加入连接
     *
     * @param socketIOClient
     */
    public void saveClient(SocketIOClient socketIOClient) {
        MyClientUser.AllSocketMap.put(socketIOClient.getSessionId(), socketIOClient);
    }

    /**
     * 断开连接
     *
     * @param socketIOClient
     */
    public void removeClient(SocketIOClient socketIOClient) {
        MyClientUser.AllSocketMap.remove(socketIOClient.getSessionId());
        LoginUserInfo loginUserInfo = MyClientUser.LoginUserInfoMap.get(socketIOClient.getSessionId());
        if (loginUserInfo != null) {
            MyClientUser.LoginUserInfoMap.remove(socketIOClient.getSessionId());
        }
    }

    /**
     * 登录
     *
     * @param jwtToken
     * @param socketIOClient
     * @param deviceType
     */
    public synchronized void  loginClient(JwtToken jwtToken, SocketIOClient socketIOClient, String deviceType, String deviceId) {
        if (StringUtils.isBlank(deviceType)) {
            deviceType = "PC";
        }
        if(jwtToken==null){
            return;
        }
        // Member  =>  ${UserId}  =>  socketIOClient}
        SocketIOClient currSocketIOClient = MyClientUser.LoginSocketMap.get(jwtToken.decodeID());
        if (currSocketIOClient == null) {
            currSocketIOClient = socketIOClient;
        }

        // 存储登录 SocketIOClient
        MyClientUser.LoginSocketMap.put(jwtToken.decodeID(), socketIOClient);

        // 存储 登录用户信息
        MyClientUser.LoginUserInfoMap.put(socketIOClient.getSessionId(), LoginUserInfo.builder()
                .userId(jwtToken.decodeID())
                .role(jwtToken.getRole())
                .deviceType(deviceType)
                .deviceId(deviceId)
                .build());
    }

    /**
     * 解析token字符串为可用对象
     *
     * @param message
     * @return
     */
    public JwtToken parseToken(MyMessage message) {
        return tokenValidate.checkToken(message.getToken(), message.getPlatform());
    }

    /**
     * 消息推送-单个用户
     * @param message
     * @return
     */
    public ApiResult sendMessageToUser(MyMessage message) {
        SocketIOClient socketIOClient = MyClientUser.LoginSocketMap.get(message.getUserId());
        if (socketIOClient == null) {
            log.info("接收用户 {} 不在线", message.getUserId());
            return ApiResult.success("接收用户 【" + message.getUserId() + "】 当前不在线");
        }
        // socketio-推送消息
        socketIOClient.sendEvent("newSocketIO-ServerMessage", MyMessage.builder()
                .userId(message.getUserId())
                .eventType(StringUtils.isBlank(message.getEventType()) ? "NORMAL" : message.getEventType())
                .message(message.getMessage())
                .build());
        log.info("socketio-推送消息"+JSON.toJSONString(message));
        return ApiResult.success("发送成功!");
    }


}
